package com.xiong.wuliao.HomeGame;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PlayerDao {
	private DataBaseOpenHelper helper = null;

	public PlayerDao(Context context) {
		helper = new DataBaseOpenHelper(context);
	}

	/**
	 *
	 * 
	 * @param playerBean
	 */
	public void update(PlayerBean playerBean) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(DataBaseOpenHelper.TABLE_SCORE, playerBean.getScore());
		db.update(DataBaseOpenHelper.TABLE_PLAYER, values, "name=?",
				new String[] { playerBean.getName() });
	}

	/**
	 *
	 * 
	 * @param name
	 * @return
	 */
	public boolean isExitName(String name) {
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.query(DataBaseOpenHelper.TABLE_PLAYER, null,
				"name=?", new String[] { name }, null, null, null);
		if (cursor == null || !cursor.moveToNext()) {
			return false;
		}
		cursor.close();
		db.close();
		return true;
	}

	/**
	 *
	 * 
	 * @param playerBean
	 */
	public void add(PlayerBean playerBean) {
		if (isExitName(playerBean.getName())) {
			update(playerBean);
		} else {
			insert(playerBean);
		}
	}

	public List<PlayerBean> findAll() {
		List<PlayerBean> list = new ArrayList<PlayerBean>();
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.query(DataBaseOpenHelper.TABLE_PLAYER, null, null,
				null, null, null, "score desc");
		if (cursor == null) {
			return null;
		}
		while (cursor.moveToNext()) {
			int id = cursor.getInt(0);
			String name = cursor.getString(1);
			int score = cursor.getInt(2);
			PlayerBean playerBean = new PlayerBean();
			playerBean.setId(id);
			playerBean.setName(name);
			playerBean.setScore(score);
			list.add(playerBean);

		}
		cursor.close();
		db.close();
		return list;
	}

	/**
	 *
	 * 
	 * @param playerBean
	 */
	public void insert(PlayerBean playerBean) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(DataBaseOpenHelper.TABLE_NAME, playerBean.getName());
		values.put(DataBaseOpenHelper.TABLE_SCORE, playerBean.getScore());
		db.insert(DataBaseOpenHelper.TABLE_PLAYER, null, values);
		db.close();
	}

}
